﻿using System;
using System.Data.SqlClient;
using BikeBouncer.BusinessLayer.Entities;
using BikeBouncer.BusinessLayer.Enums;
using Devv.Core.UniDataTier;

namespace BikeBouncer.BusinessLayer
{
	public partial class DataAccess
	{
		#region Get

		public static SqlDataReader Item_Get(Int32 id)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@ItemId", id);

			return (SqlDataReader)db.ExecuteReader("upItem_Get");
		}

		public static SqlDataReader Item_Get(User user)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@UserId", user.Id);

			return (SqlDataReader)db.ExecuteReader("upItem_Get");
		}

		public static SqlDataReader Item_Get(Address address, ItemStatus status)
		{
			DataHandler db = new DataHandler();

			if (!String.IsNullOrEmpty(address.Postcode))
			{
				db.AddParameter("@AddressPostcode", address.Postcode);
			}

			if (address.City.Id > 0)
			{
				db.AddParameter("@CityId", address.City.Id);
			}

			if (!String.IsNullOrEmpty(address.City.Title))
			{
				db.AddParameter("@CityTitle", address.City.Title);
			}

			if (!String.IsNullOrEmpty(address.City.Country))
			{
				db.AddParameter("@CityCountry", address.City.Country);
			}

			db.AddParameter("@StatusId", (Int32)status);

			return (SqlDataReader)db.ExecuteReader("upItem_Get");
		}

		public static SqlDataReader Item_GetBySerial(String serial)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@Serial", serial);

			return (SqlDataReader)db.ExecuteReader("upItem_Get");
		}

		public static SqlDataReader Item_Fetch(String keywords)
		{
			keywords = DataParser.ParseKeywords(keywords);

			if (String.IsNullOrEmpty(keywords))
			{
				return null;
			}

			DataHandler db = new DataHandler();

			db.AddParameter("@Keywords", keywords);

			return (SqlDataReader)db.ExecuteReader("upItem_Get");
		}

		#endregion

		#region Insert and update

		public static void Item_Upsert(Item item)
		{
			using (DataHandler db = new DataHandler())
			{
				db.AddParameter("@MakerId", item.Maker.Id);
				db.AddParameter("@UserId", item.User.Id);
				db.AddParameter("@StatusId", (Int32)item.Status);
				db.AddParameter("@Title", item.Title);
				db.AddParameter("@Details", item.Details, true);
				db.AddParameter("@Serial", item.Serial, true);
				db.AddParameter("@Colors", item.Colors, true); 
				db.AddParameter("@Active", item.Active);

				if (item.Id > 0)
				{
					db.AddParameter("@ItemId", item.Id);
					db.AddParameter("@StatusDate", item.StatusDate);

					db.ExecuteScalar("upItem_Update");
				}
				else
				{
					item.Id = Convert.ToInt32(db.ExecuteScalar("upItem_Insert"));

					MailManager.ItemRegistrationComplete(item);
				}
			}
		}

		#endregion
	}
}